<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

</body>
<script>

//对象浅拷贝和深拷贝的唯一区别是：深拷贝的时候，当遇到对象的属性值为对象类型的时候，会进行递归复制，直至对象的属性为值类型为止。

//浅拷贝

//for in 循环 ================================================

    function simple(initojb){
        var obj = {};
        for(var i in initojb){
              obj[i] = initojb[i];
        };
        return obj;
    }


    var obj = {
        a:1,
        b:2,
        c:3,
        d:{
            d1:1,
            d2:2
        }
    };

    var cloneobj = simple(obj);

    cloneobj.d.d1 = 2;

    console.log(obj,cloneobj)

//深拷贝

//JSON方法 ====================

var obj = {
    a:1,
    b:2,
    c:{
        c1:1,
        c2:2
    }
};



var jsonobj = JSON.parse(JSON.stringify(obj));

jsonobj.c.c1 = 2;

console.log(obj,jsonobj);


// 递归调用复制的方法


function deepClone1(obj,cloneObj){
    if(typeof obj != 'object'){
        return false;
    }
    var cloneObj = cloneObj || {};
    for(var i in obj){
        if(typeof obj[i] === 'object'){
            cloneObj[i] = (obj[i] instanceof Array) ? [] : {};
            deepClone1(obj[i],cloneObj[i]);
        }else{
            cloneObj[i] = obj[i];
        }
    }
    return cloneObj;
}

var obj1={a:1,b:2,c:[1,2,3]};
var obj2=deepClone1(obj1);
console.log(obj1.c); //[1,2,3]
console.log(obj2.c); //[1,2,3]
obj2.c.push(4);
console.log(obj2.c); //[1,2,3,4]
console.log(obj1.c); //[1,2,3]



</script>
</html>